package com.lt.schoolchat.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lt.schoolchat.common.BaseResponse;
import com.lt.schoolchat.common.ErrorCode;
import com.lt.schoolchat.common.PageRequest;
import com.lt.schoolchat.common.ResultUtils;
import com.lt.schoolchat.exception.BusinessException;
import com.lt.schoolchat.model.dto.smallvideo.SmallVideoQueryRequest;
import com.lt.schoolchat.model.dto.smallvideo.SmallVideoUpdateRequest;
import com.lt.schoolchat.model.dto.smallvideo.SmallVideoAddRequest;
import com.lt.schoolchat.model.entity.User;
import com.lt.schoolchat.model.mongo.Video;
import com.lt.schoolchat.model.vo.VideoVO;
import com.lt.schoolchat.service.CommentService;
import com.lt.schoolchat.service.SmallVideosService;
import com.lt.schoolchat.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.*;

/**
 * @description: 小视频接口
 * @author: ~Teng~
 * @date: 2023/5/17 10:45
 */
@RestController
@RequestMapping("/smallVideos")
@Api(tags = "小视频接口")
@Slf4j
public class SmallVideosController {
    @Resource
    private SmallVideosService smallVideosService;
    @Resource
    private UserService userService;
    @Resource
    private CommentService commentService;

    // IO 型线程池
    private final ExecutorService ioExecutorService = new ThreadPoolExecutor(4, 20, 10, TimeUnit.MINUTES,
            new ArrayBlockingQueue<>(10000));

    @PostMapping("/add")
    @ApiOperation("发布小视频")
    public BaseResponse<Boolean> saveVideo(@RequestBody SmallVideoAddRequest smallVideoAddRequest,
                                           HttpServletRequest request) {
        if (smallVideoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String videoFileUrl = smallVideoAddRequest.getVideoFileUrl();
        String videoThumbnailUrl = smallVideoAddRequest.getVideoThumbnailUrl();
        if (StringUtils.isAnyBlank(videoThumbnailUrl, videoFileUrl)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "封面和视频不能为空");
        }
        String text = smallVideoAddRequest.getText();
        Long userId = loginUser.getId();
        smallVideosService.saveVideo(videoThumbnailUrl, videoFileUrl, text, userId);
        return ResultUtils.success(Boolean.TRUE);
    }

    @PostMapping("/update")
    @ApiOperation("更新小视频")
    public BaseResponse<Boolean> updateVideo(@RequestBody SmallVideoUpdateRequest smallVideoUpdateRequest,
                                             HttpServletRequest request) {
        if (smallVideoUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String videoFileUrl = smallVideoUpdateRequest.getVideoFileUrl();
        String videoThumbnailUrl = smallVideoUpdateRequest.getVideoThumbnailUrl();
        if (StringUtils.isAnyBlank(videoThumbnailUrl, videoFileUrl)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "封面和视频不能为空");
        }
        String text = smallVideoUpdateRequest.getText();
        Long userId = loginUser.getId();
        String id = smallVideoUpdateRequest.getId();
        smallVideosService.updateVideo(new ObjectId(id), videoThumbnailUrl, videoFileUrl, text, userId);
        return ResultUtils.success(Boolean.TRUE);
    }

    @GetMapping("/list/page/{userId}")
    @ApiOperation("分页查询某个用户小视频列表")
    public BaseResponse<Page<VideoVO>> queryVideoListByUserId(@PathVariable("userId") Long userId, PageRequest pageRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (pageRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = pageRequest.getCurrent();
        long pageSize = pageRequest.getPageSize();
        if (current <= 0 || pageSize <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (userId == null || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Page<VideoVO> result = smallVideosService.queryVideoList(current, pageSize, null, userId);
        return ResultUtils.success(result);
    }

    ///////////////////后台管理//////////////////////////
    @GetMapping("/list/page")
    @ApiOperation("分页查询所有用户小视频列表（后台）")
    public BaseResponse<Page<VideoVO>> queryVideoList(SmallVideoQueryRequest smallVideoQueryRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (smallVideoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = smallVideoQueryRequest.getCurrent();
        long pageSize = smallVideoQueryRequest.getPageSize();
        if (current <= 0 || pageSize <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Integer likeCount = smallVideoQueryRequest.getLikeCount();
        Page<VideoVO> result = smallVideosService.queryVideoList(current, pageSize, likeCount, null);
        return ResultUtils.success(result);
    }

    @PostMapping("/delete")
    @ApiOperation("删除小视频")
    public BaseResponse<Boolean> deleteSmallVideo(String id, HttpServletRequest request) {
        if (StringUtils.isBlank(id)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        // 判断是否存在
        Video video = smallVideosService.getVideoById(new ObjectId(id));
        if (video == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!video.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        smallVideosService.removeById(new ObjectId(id));
        // 异步删除小视频点赞信息
        CompletableFuture.runAsync(() -> commentService.removeCommentByVideoId(new ObjectId(id)), ioExecutorService);
        return ResultUtils.success(Boolean.TRUE);
    }

    @GetMapping("/get")
    @ApiOperation("根据id获取小视频")
    public BaseResponse<VideoVO> getVideoById(String id, HttpServletRequest request) {
        if (StringUtils.isBlank(id)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        Video video = smallVideosService.getVideoById(new ObjectId(id));
        VideoVO videoVO = VideoVO.init(loginUser, video);
        return ResultUtils.success(videoVO);
    }
}
